package com.vzaar
{
	import com.adobe.serialization.json.JSON;
	import com.vzaar.type.VzaarVideoProfile;
	import com.vzaar.uploader.S3UploadOptions;
	import com.vzaar.uploader.S3Uploader;

	import flash.events.DataEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.HTTPStatusEvent;
	import flash.events.IEventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileReference;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestHeader;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import flash.xml.XMLDocument;
	import flash.xml.XMLNode;

	import net.oauth.OAuthConsumer;
	import net.oauth.OAuthRequest;
	import net.oauth.OAuthSignatureMethod_HMAC_SHA1;
	import net.oauth.OAuthToken;
	import net.oauth.URLEncoding;

	[Event(name="open", type="flash.events.Event.OPEN")]
	[Event(name="uploadCompleteData", type="flash.events.DataEvent.UPLOAD_COMPLETE_DATA")]        
	[Event(name="ioError", type="flash.events.IOErrorEvent.IO_ERROR")]
	[Event(name="securityError", type="flash.events.SecurityErrorEvent.SECURITY_ERROR")]
	[Event(name="progress", type="flash.events.ProgressEvent.PROGRESS")]
	
	[Event(name="vzaar_account_details", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_user_details", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_video_details", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_video_list", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_who_am_i", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_upload_signature", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_searched_video_list", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_complete", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_upload_complete", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_processing_complete", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_video_deleted", type="com.vzaar.VzaarEvent")]
	[Event(name="vzaar_upload_edited", type="com.vzaar.VzaarEvent")]
	
	public class Vzaar extends EventDispatcher
	{
		private var dataReceived:String ;
		
		private var _token:String = '';
		
		[Bindable]
		public function get token():String
		{
			return _token;
		}
		
		public function set token(value:String):void
		{
			_token = value;
		}
		
		private var _secret:String = '';
		
		[Bindable]
		public function get secret():String
		{
			return _secret;
		}
		
		public function set secret(value:String):void
		{
			_secret = value;
		}
		
		private var _enableFlashSupport:Boolean = false;
		
		public function get enableFlashSupport():Boolean
		{
			return _enableFlashSupport;
		}
		
		public function set enableFlashSupport(value:Boolean):void
		{
			_enableFlashSupport = value;
		}
		
		public static const URL_LIVE:String = "http://vzaar.com/";
		public static const AMAZON_S3_URL:String = '.s3.amazonaws.com/';
		
		public var guid:String;

		public function Vzaar(token:String, secret:String):void
		{
			this._token = token;
			this._secret = secret;
			
			//dataReceived = new ByteArray();
		}
		
		public function getUserEndpoint(user:String):String {
			return URL_LIVE + 'users/' + user + '.json';
		}
		
		public function getVideosEndpoint(user:String, count:int=1):String {
			return URL_LIVE + 'api/' + user + '/videos.json?count=' + count;
		}
		
		public function setAuth(url:String, method:String='GET'):OAuthRequest 
		{
			var _consumer:OAuthConsumer = new OAuthConsumer("", "");
			var _token:OAuthToken = new OAuthToken(secret, token);
			var _req:OAuthRequest = new OAuthRequest(method, url, null, _consumer, _token);					
			
			return _req; 
		}	    	    
		
		public function whoAmI():void 
		{
			var _url:String = URL_LIVE + 'api/test/whoami.json';
			var userAgent:URLRequestHeader = new URLRequestHeader("User-Agent"," Vzaar OAuth Client");
			getURLRequestedResponse(_url,VzaarEvent.VZAAR_WHO_AM_I,true );			
		}
				
		/**
		 * This API call returns the details and rights for each vzaar account
		 * type along with it's relevant metadata
		 * http://vzaar.com/api/accounts/{account}.json
		 *  var accountType:AccountType = new AccountType();
		 *	accountType.accountId = decoder.account_id;
		 *	accountType.bandwidth = decoder.bandwidth;
		 *	accountType.currency = decoder.cost.currency;
		 *	accountType.monthly = decoder.cost.monthly;
		 *	accountType.isBorderless = decoder.rights.borderless;
		 *	accountType.isSearchEnhancer = decoder.rights.searchEnhancer;
		 *	accountType.title = decoder.title;
		 *	accountType.version = decoder.version;
		 * 
		 * @param account integer $account is the vzaar account type. This is an integer.
		 * @return AccountType
		 * 
		 */
		public function getAccountDetails(account:int):void
		{
			var _url:String = URL_LIVE + 'api/accounts/' + account.toString() + '.json';
			getURLRequestedResponse(_url,VzaarEvent.VZAAR_ACCOUNT_DETAILS);
			
			/*var accountType:AccountType = new AccountType();
			accountType.accountId = decoder.account_id;
			accountType.bandwidth = decoder.bandwidth;
			accountType.currency = decoder.cost.currency;
			accountType.monthly = decoder.cost.monthly;
			accountType.isBorderless = decoder.rights.borderless;
			accountType.isSearchEnhancer = decoder.rights.searchEnhancer;
			accountType.title = decoder.title;
			accountType.version = decoder.version;*/			
		}
		
		/**
		 * This API call returns the user's public details along with it's relevant metadata
		 * @static
		 * @param  $account
		 * @return User
		 */
		public function getUserDetails(account:String):void
		{
			var _url:String = URL_LIVE + 'api/' + account + '.json';
			
			getURLRequestedResponse(_url , VzaarEvent.VZAAR_USER_DETAILS);
								
		}
		
		/**
		 * This API call returns a list of the user's active videos along with it's
		 * relevant metadata
		 * http://vzaar.com/api/vzaar/videos.xml?title=vzaar
		 * @static
		 * @param string $username is the vzaar login name for the user. Note: This must be the username and not the email address
		 * @param bool $auth
		 * @param integer $count
		 * @param string $labels
		 * @param string $status
		 * @return VideoList
		 */
		public function getVideoList(username:String, auth:Boolean = false, count:int = 20, labels:String = "", status:String = ""):void
		{
			var _url:String = URL_LIVE + 'api/' + username + '/videos.json?count=' + count;
			
			if ( labels != "" ) _url += "&labels=" + labels;
			if ( status != "") _url += '&status' + status;
			
			getURLRequestedResponse(_url,VzaarEvent.VZAAR_VIDEO_LIST,auth);
			
			/*var videoList:Array = new Array();
			for each (var obj:Object in decoder)
			{
			var video:VzaarVideo = new VzaarVideo();
			video.createdAt = obj.created_at;
			video.duration = obj.duration;
			video.height = obj.height;
			video.id = obj.id;
			video.playCount = obj.play_count;
			video.thumbnail = obj.thumbnail;
			video.title = obj.title;
			video.url = obj.url;
			video.status = obj.status;
			video.status_id = obj.status_id;
			video.version = obj.version;
			video.width = obj.width;
			var user:VzaarUser = new VzaarUser();
			user.authorAccount = obj.user.author_account;
			user.authorName = obj.user.author_name;
			user.authorUrl = obj.user.author_url;
			user.videoCount = obj.user.video_count;
			video.user = user; 
			
			videoList.push(video);
			}*/
		}
		
		/**
		 * This API call returns a list of the user's active videos along with it's
		 * relevant metadata
		 * @param string $username the vzaar login name for the user. Note: This must be the actual username and not the email address
		 * @param bool $auth Use authenticated request if true
		 * @param string $title Return only videos with title containing given string
		 * @param string $labels
		 * @param integer $count Specifies the number of videos to retrieve per page. Default is 20. Maximum is 100
		 * @param integer $page Specifies the page number to retrieve. Default is 1
		 * @param string $sort Values can be asc (least_recent) or desc (most_recent). Defaults to desc
		 * @return VideoList
		 */
		public function searchVideoList(username:String, auth:Boolean = false, title:String = '', labels:String = '', count:int = 20, page:int = 1, sort:String = 'desc'):void
		{
			var _url:String = URL_LIVE + 'api/' + username + '/videos.json?count=' + count + '&page=' + page + '&sort=' + sort;
			if ( labels != '') _url += "&labels=" + labels;
			if ( title != '') _url += '&title=' + URLEncoding.encode(title);
			
			getURLRequestedResponse(_url,VzaarEvent.VZAAR_SEARCHED_VIDEO_LIST,auth);
			
			/*var videoList:Array = new Array();
			for each (var obj:Object in decoder)
			{
			var video:VzaarVideo = new VzaarVideo();
			video.createdAt = obj.created_at;
			video.duration = obj.duration;
			video.height = obj.height;
			video.id = obj.id;
			video.playCount = obj.play_count;
			video.thumbnail = obj.thumbnail;
			video.title = obj.title;
			video.url = obj.url;
			video.status = obj.status;
			video.status_id = obj.status_id;
			video.version = obj.version;
			video.width = obj.width;
			var user:VzaarUser = new VzaarUser();
			user.authorAccount = obj.user.author_account;
			user.authorName = obj.user.author_name;
			user.authorUrl = obj.user.author_url;
			user.videoCount = obj.user.video_count;
			video.user = user; 
			
			videoList.push(video);
			}			*/
		}
		
		/**
		 * vzaar uses the oEmbed open standard for allowing 3rd parties to
		 * integrated with the vzaar. You can use the vzaar video URL to easily
		 * obtain the appropriate embed code for that video
		 * @param integer $id is the vzaar video number for that video
		 * @param bool $auth Use authenticated request if true
		 * @return VideoDetails
		 */
		public function getVideoDetails(id:Number, auth:Boolean = false):void
		{
			var _url:String = URL_LIVE + 'api/videos/' + id.toString() + '.json';
			
			getURLRequestedResponse(_url,VzaarEvent.VZAAR_VIDEO_DETAILS,auth);
			
			/*this.addEventListener(VzaarEvent.VZAAR_USER_DETAILS , function (e:VzaarEvent):void
			{
				var decoder:Object = e.result;
				
				vidDetails = new VzaarVideoDetails();
				vidDetails.author_account = decoder.author_account;
				vidDetails.author_name = decoder.author_name;
				vidDetails.author_url = decoder.author_url;
				vidDetails.duration = decoder.duration;
				vidDetails.framegrab_height = decoder.framegrab_height;
				vidDetails.framegrab_url = decoder.framegrab_url;
				vidDetails.framegrab_width = decoder.framegrab_width;
				vidDetails.height = decoder.height;
				vidDetails.html = decoder.html;
				vidDetails.playCount = decoder.playCount;
				vidDetails.provider_name = decoder.provider_name;
				vidDetails.provider_url = decoder.provider_url;
				vidDetails.thumbnail_height = decoder.thumbnail_height;
				vidDetails.thumbnail_url = decoder.thumbnail_url;
				vidDetails.thumbnail_width = decoder.thumbnail_width;
				vidDetails.title = decoder.title;
				vidDetails.type = decoder.type;
				vidDetails.version = decoder.version;
				vidDetails.video_status_description = decoder.video_status_description;
				vidDetails.video_status_id = decoder.video_status_id;
				vidDetails.video_url = decoder.video_url;
				vidDetails.width = decoder.width;
			});
				
			return vidDetails;*/
		}
		
		private function configureURLListeners(dispatcher:IEventDispatcher):void 
		{			
			dispatcher.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
			//dispatcher.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, httpStatusHandler);
			dispatcher.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
		}
		
		private function securityErrorHandler(event:SecurityErrorEvent):void 
		{
			trace("securityErrorHandler: " + event.toString());
		}
		
		private function httpStatusHandler(event:HTTPStatusEvent):void 
		{
			trace("httpStatusHandler: " + event.toString());
		}
		
		private function ioErrorHandler(event:IOErrorEvent):void
		{
			trace("ioErrorHandler: " + event.toString());
		}
		
		private function getURLRequestedResponse(url:String,eventType:String = "",isAuth:Boolean = false,headers:Array = null,data:String = "",method:String = "GET",noAuth:Boolean = false,isUrlVar:Boolean = false,fileRef:FileReference = null ):void
		{
			var loader:URLLoader = new URLLoader();
			configureURLListeners(loader);
			loader.addEventListener(Event.COMPLETE , function (e:Event):void
			{
				var loader:URLLoader = URLLoader(e.target);
				
				if (eventType != "")
				{					
					if (loader.data.toString().search('xml') != -1)
					{
						if (fileRef != null)
							dispatchEvent(new VzaarEvent(eventType,loader.data,'xml',fileRef));
						else
							dispatchEvent(new VzaarEvent(eventType,loader.data,'xml'));
					}
					else
					{
						var decoder:Object = JSON.decode(loader.data);
						
						if (fileRef != null)
							dispatchEvent(new VzaarEvent(eventType,decoder,'json',fileRef));
						else
							dispatchEvent(new VzaarEvent(eventType,decoder,'json'));
					}
				}				
			});
			
			var req:OAuthRequest = setAuth(url,method);	
			
			var request:URLRequest = new URLRequest(req.buildRequest(new OAuthSignatureMethod_HMAC_SHA1(), OAuthRequest.RESULT_TYPE_URL_STRING));			
			request.method = method;
			
			if ( data != "")
			{			
				if (isUrlVar)
					request.data = new URLVariables(data);
				else
					request.data = data;
			}
			
			if (isAuth)
			{
				if (!noAuth)
				{
					//the Authorization header is allready included
					//request.requestHeaders.push(req.buildRequest(new OAuthSignatureMethod_HMAC_SHA1(),OAuthRequest.RESULT_TYPE_HEADER));
				}
				if ( headers != null)
				{
					for each (var header:URLRequestHeader in headers)
					{
						request.requestHeaders.push(header);
					}	
				}
			}
			
			try 
			{
				loader.load(request);
			} catch (error:Error) 
			{
				trace("Unable to load requested document.");
			}	
		}
		
		/*private function getRequestedResponse(url:String,eventType:String = "",isAuth:Boolean = false,headers:Array = null,data:String = "",method:String = "GET",noAuth:Boolean = false,isUrlVar:Boolean = false,fileRef:FileReference = null ):void
		{
			var client:HttpClient = new HttpClient();

			configureListeners(client.listener);		
			client.listener.onComplete = function (e:HttpResponseEvent):void
			{		
				if (dataReceived != "" )
				{
					if (eventType != "")
					{					
						if (dataReceived.search('xml') != -1)
						{
							if (fileRef != null)
								dispatchEvent(new VzaarEvent(eventType,XML(dataReceived),'xml',fileRef));
							else
								dispatchEvent(new VzaarEvent(eventType,XML(dataReceived),'xml'));
						}
						else
						{
							var s:String = dataReceived;
							
							var decoder:Object = JSON.decode(dataReceived);
							
							if (fileRef != null)
								dispatchEvent(new VzaarEvent(eventType,decoder,'json',fileRef));
							else
								dispatchEvent(new VzaarEvent(eventType,decoder,'json'));
						}
					}		
				}
				else
				{
					throw new Error("No data available!");
				}
			};
			
			var req:OAuthRequest = setAuth(url,method);	
			
			var uri:URI = new URI(req.requestURL);
			var request:HttpRequest;
			
			switch(method)
			{				
				case URLRequestMethod.GET:
				{
					request = new Get();
					break;
				}			
					
				case URLRequestMethod.POST:
				{
					request = new Post();
					break;
				}
					
				case URLRequestMethod.DELETE:
				{
					request = new Delete();
					break;
				}	
			}
			
			buildRequestSettings(request,req,isAuth,headers,data,noAuth,isUrlVar);
			client.request(uri,request);
		}*/
		
		/*private function buildRequestSettings(request:HttpRequest, req:OAuthRequest ,isAuth:Boolean = false,headers:Array = null,data:String = "",noAuth:Boolean = false,isUrlVar:Boolean = false):void
		{
			if ( data != "")
			{			
				if (isUrlVar)
					request.body = new URLVariables(data);
				else
				{
					var dataForBody:ByteArray = new ByteArray();
					dataForBody.writeUTFBytes(data);
					dataForBody.position = 0;
					request.body = dataForBody;
				}
			}
			
			if (isAuth)
			{
				if (!noAuth)
				{
					//the Authorization header is allready included
					var authHeader:URLRequestHeader = req.buildRequest(new OAuthSignatureMethod_HMAC_SHA1(),OAuthRequest.RESULT_TYPE_HEADER); 
					request.addHeader(authHeader.name, authHeader.value);
				}
				if ( headers != null)
				{
					for each (var header:URLRequestHeader in headers)
					{
						request.addHeader(header.name,header.value);
					}	
				}
			}
		}
		
		private function configureListeners(dispatcher:HttpListener):void 
		{			
			dispatcher.onData = function(event:HttpDataEvent):void
			{
				// Notified with response content in event.bytes as it streams in				
				dataReceived = event.readUTFBytes();
			};				
			
			dispatcher.onError = function (event:HttpErrorEvent):void
			{
				throw new IOError(event.toString());
			};
			
		}*/
		
		/**
		 * Get Upload Signature
		 * @static
		 * @param null $redirectUrl In case if you are using redirection after your upload, specify redirect URL
		 * @return array
		 */
		public function getUploadSignature(redirectUrl:String = "",fileRef:FileReference = null):void
		{
			var _url:String = URL_LIVE + "api/videos/signature";			
			
			if (enableFlashSupport)
			{
				_url += '?flash_request=true';
			}
			
			if (redirectUrl != "")
			{
				if (enableFlashSupport)
				{
					_url += '&success_action_redirect=' + redirectUrl;
				}
				else
				{
					_url += '?success_action_redirect=' + redirectUrl;
				}
			}
			
			var userAgentHeader:URLRequestHeader = new URLRequestHeader('User-Agent', 'Vzaar OAuth Client');
			if (fileRef != null)
				getURLRequestedResponse(_url , VzaarEvent.VZAAR_UPLOAD_SIGNATURE , true,[userAgentHeader],"",URLRequestMethod.GET,false,false,fileRef);
			else
				getURLRequestedResponse(_url , VzaarEvent.VZAAR_UPLOAD_SIGNATURE , true,[userAgentHeader]);
		}
		
		/**
		 * Upload video from local drive directly to Amazon S3 bucket
		 * @param string $path
		 * @return string GUID of the file uploaded
		 */
		public function uploadVideo(file:FileReference):void
		{
			var url:String = "http://vzaarphp.mywdk.com/s3_upload/signature.php";
			var service:URLLoader = new URLLoader();
			service.addEventListener(Event.COMPLETE , function (e:Event):void
			{
				var loader:URLLoader = URLLoader(e.target);
								
				
				var result:XML = XML(loader.data.toString());
				
				var uploadOptions:S3UploadOptions = new S3UploadOptions();
				guid = result.guid;
				uploadOptions.acl = result.acl;
				uploadOptions.policy = result.policy;
				uploadOptions.signature = result.signature;
				uploadOptions.contentType = 'binary/octet-stream';
				
				uploadOptions.secure = result.https;												
				
				var s3Uploader:S3Uploader = new S3Uploader(result.accesskeyid ,
					result.key , 
					result.bucket,
					result.expirationdate,
					uploadOptions);
				
				s3Uploader.addEventListener(Event.OPEN, onOpen);
				s3Uploader.addEventListener(ProgressEvent.PROGRESS,onProgress);									
				s3Uploader.addEventListener(IOErrorEvent.IO_ERROR,onIOError);			
				s3Uploader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onSecurityError);			
				s3Uploader.addEventListener(DataEvent.UPLOAD_COMPLETE_DATA, onUploadComplete);			
				s3Uploader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onHttpStatus);					
				
				s3Uploader.upload(file);
			});
			
			var urlReq:URLRequest = new URLRequest(url);
			urlReq.method = URLRequestMethod.GET;
			
			try 
			{
				service.load(urlReq);
			} catch (error:Error) 
			{
				trace("Unable to load requested document.");
			}								
		}
		
		protected function onHttpStatus(event:HTTPStatusEvent):void
		{
			trace("STATUS: -----------  " + event.status)
			if(Math.floor(event.status/100) == 2) {
				this.dispatchEvent(new DataEvent(DataEvent.UPLOAD_COMPLETE_DATA, event.bubbles, event.cancelable, "Amazon S3 returned HTTP status " + event.status.toString() + "."));
			} else {
				this.dispatchEvent(new IOErrorEvent(IOErrorEvent.IO_ERROR, event.bubbles, event.cancelable, "Amazon S3 returned an error: HTTP status " + event.status.toString() + "."));
			}
		}
		
		protected function onUploadComplete(e:DataEvent):void
		{
			var data:String = e.data;
			
			if(isError(data)) {
				this.dispatchEvent(
					new IOErrorEvent(IOErrorEvent.IO_ERROR, e.bubbles, e.cancelable, "Amazon S3 returned an error: " + data + ".")
				);
			} else {
				this.dispatchEvent(new DataEvent(DataEvent.UPLOAD_COMPLETE_DATA, e.bubbles, e.cancelable, data));
				dispatchEvent(new VzaarEvent(VzaarEvent.VZAAR_UPLOAD_COMPLETE,e.data));
			}
		}
		
		private function isError(responseText:String):Boolean {
			var xml:XMLDocument = new XMLDocument();
			xml.ignoreWhite = true;
			xml.parseXML(responseText);
			var root:XMLNode = xml.firstChild;
			if( root == null || root.nodeName != "Error" )
			{
				return false;
			}
			return true;
		}
		
		protected function onSecurityError(event:SecurityErrorEvent):void
		{
			this.dispatchEvent(event);
		}
		
		protected function onIOError(event:IOErrorEvent):void
		{
			this.dispatchEvent(event);
		}
		
		protected function onProgress(event:ProgressEvent):void
		{
			this.dispatchEvent(event);
		}
		
		protected function onOpen(event:Event):void
		{
			this.dispatchEvent(event);
		}
		
		/**
		 * Delete video by its ID
		 * @static
		 * @param  $id vzaar Video ID
		 * @return HttpMessage|mixed
		 */
		public function deleteVideo(id:int):void
		{
			var _url:String = URL_LIVE + "api/videos/" + id + ".xml";
			
			var data:String = '<?xml version="1.0" encoding="UTF-8"?><vzaar-api><_method>delete</_method></vzaar-api>';
			
			var headerUserAgent:URLRequestHeader = new URLRequestHeader('User-Agent', 'Vzaar OAuth Client');
			var headerConnection:URLRequestHeader = new URLRequestHeader('Connection' ,'close');
			var headerContentType:URLRequestHeader = new URLRequestHeader('Content-Type' , 'application/xml');
			
			getURLRequestedResponse(_url, VzaarEvent.VZAAR_VIDEO_DELETED ,true , [] , data , URLRequestMethod.POST);
		}
		
		public  function editVideo(id:String, title:String, description:String, isPrivate:String = 'false', seoUrl:String = ''):void
		{
			var _url:String = URL_LIVE + "api/videos/" + id + ".xml";
						
			var data:String = '<?xml version="1.0" encoding="UTF-8"?><vzaar-api><_method>put</_method><video><title>' + title +
				'</title><description>' + description + '</description>';
			
			if ( isPrivate != '') data += '<private>' + isPrivate + '</private>';
			if ( seoUrl != '') data += '<seo_url>' + seoUrl + '</seo_url>';
			
			data += '</video></vzaar-api>';
			
			var headerUserAgent:URLRequestHeader = new URLRequestHeader('User-Agent', 'Vzaar OAuth Client');
			var headerConnection:URLRequestHeader = new URLRequestHeader('Connection' ,'close');
			var headerContentType:URLRequestHeader = new URLRequestHeader('Content-Type' , 'application/xml');
			
			getURLRequestedResponse(_url, VzaarEvent.VZAAR_VIDEO_EDITED ,true , [] , data , URLRequestMethod.POST);			
		}
		
		/**
		 * This API call tells the vzaar system to process a newly uploaded video. This will encode it if necessary and
		 * then provide a vzaar video idea back.
		 * http://developer.vzaar.com/docs/version_1.0/uploading/process
		 * @static
		 * @param string $guid Specifies the guid to operate on
		 * @param string $title Specifies the title for the video
		 * @param string $description Specifies the description for the video
		 * @param string $labels
		 * @param int|\Profile $profile Specifies the size for the video to be encoded in. If not specified, this will use the vzaar default
		 * @param boolean $transcoding If True forces vzaar to transcode the video, false makes vzaar use the original source file (available only for mp4 and flv files)
		 * @param string $replace Specifies the video ID of an existing video that you wish to replace with the new video.
		 * @return string
		 */
		public function processVideo(guid:String, title:String, description:String, labels:String, profile:int = VzaarVideoProfile.MEDIUM , transcoding:Boolean = false, replace:String = ''):void
		{
			var _url:String = URL_LIVE + "api/videos";
			
			if (replace != '') replace = '<replace_id>' + replace + '</replace_id>';
			
			var data:String = '<?xml version="1.0" encoding="UTF-8"?><vzaar-api><video>' + replace + '<guid>' + guid + '</guid><title>' +
				title + '</title><description>' + description + '</description><labels>' +
				labels + '</labels><profile>' + profile + '</profile>';
			
			if (transcoding) data += '<transcoding>true</transcoding>';
			
			data += '</video></vzaar-api>';
			
			/*var headerUserAgent:URLRequestHeader = new URLRequestHeader('User-Agent', 'Vzaar OAuth Client');
			var headerConnection:URLRequestHeader = new URLRequestHeader('Connection' ,'close');*/
			var headerContentType:URLRequestHeader = new URLRequestHeader('Content-Type' , 'application/xml');
			
			getURLRequestedResponse(_url , VzaarEvent.VZAAR_PROCESSING_COMPLETE , true,[headerContentType],data,URLRequestMethod.POST);						
		}
	}
}